﻿@model ContentCreator.ViewModels.ContentCreatorFieldViewModel
@using ContentCreator.Settings
@using Orchard.Settings

@{
    Script.Require("jQuery").AtHead();
    Script.Require("ContentCreator").AtFoot();
    Script.Require("jQueryUI_Sortable").AtFoot();
    Style.Include("content-create-admin.css");

    var settings = Model.Field.PartFieldDefinition.Settings.GetModel<ContentCreatorFieldSettings>();
}
<script>
    function scalePreview(img) {
        // ensures the loaded image preview fits within the preview area
        // by scaling it down if not.
        var self = $(img),
            width = self.width(),
            height = self.height(),
            aspect = width / height;
        if (width > 100) {
            width = 100;
            height = Math.round(width / aspect);
        }
        if (height > 100) {
            height = 100;
            width = Math.round(width * aspect);
        }

        self.css({
            width: width,
            height: height,
            display: "inline"
        });
    }
</script>

<fieldset>
    <label @if (settings.Required)
           {
               <text>class="required"</text>
           }>@Model.Field.DisplayName</label>
    <div id="save-message-@Html.FieldIdFor(m => m.Field.Ids)" class="message message-Warning content-creator-message">@T("You need to save your changes.")</div>
    <table id="content-creator-@Html.FieldIdFor(m => m.Field.Ids)" class="items content-creator" summary="@Model.Field.DisplayName">
        <colgroup>
            <col id="Col1" style="width: 20px" />
            <col id="Col2" />
            <col id="Col3" style="width: 20px" />
            <col id="Col4" />
        </colgroup>
        <thead>
            <tr>
                <th scope="col">&nbsp;&darr;</th>
                <th scope="col">@T("Content Item")</th>
                <th scope="col"></th>
                <th scope="col">&nbsp;</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var contentItem in Model.ContentItems)
            {
                var contentElementPath = settings.ContentElement.Split('/');
                dynamic output = Display(contentItem.ContentType);

                //Part, contentElementPath is size 2: contentType/partName
                if (contentElementPath[0] != contentElementPath[1])
                {
                    dynamic part = contentItem.Parts.FirstOrDefault(p => p.PartDefinition.Name == contentElementPath[1]);
                    switch (contentElementPath[1])
                    {
                        case "TitlePart":
                            output = Display(part.Title);
                            break;
                        case "BodyPart":
                            output = Display(Html.Raw(part.Text));
                            break;
                    }
                }
                //Field, contentElementPath is size 3: contentType/contentType/FieldName
                else
                {
                    dynamic field = contentItem.Parts.FirstOrDefault(p => p.PartDefinition.Name == contentElementPath[1]).Fields.FirstOrDefault(f => f.Name == contentElementPath[2]);
                    if (field.FieldDefinition.Name == "TextField" || field.FieldDefinition.Name == "LinkField")
                    {
                        if (field.Value.Contains("http://www.youtube.com/embed/"))
                        {
                            output = "<iframe id=\"ytplayer\" type=\"text/html\" width=\"320\" height=\"200\" src=" + field.Value + "  frameborder=\"0\"></iframe>";
                        }
                        else
                        {
                            output = field.Value;
                        }
                    }
                    else
                    {
                        if (field.FieldDefinition.Name == "NumericField"
                            || field.FieldDefinition.Name == "EnumerationField"
                            || field.FieldDefinition.Name == "InputField"
                            || field.FieldDefinition.Name == "TextField")
                        {
                            output = field.Value;
                        }
                        else
                        {
                            if (field.FieldDefinition.Name == "MediaPickerField")
                            {
                                output = "<img data-filename=" + field.Url.Substring(field.Url.LastIndexOf("/") + 1) + " alt=\"\" src=" + Url.Content(field.Url) + " onload=\" scalePreview(this) \" />";
                            }
                            else
                            {
                                if (field.FieldDefinition.Name == "BooleanField")
                                {
                                    if (field.Value == null)
                                    {
                                        output = field.PartFieldDefinition.Settings["BooleanFieldSettings.NotSetLabel"];
                                    }
                                    else
                                    {
                                        output = field.Value ? field.PartFieldDefinition.Settings["BooleanFieldSettings.OnLabel"] : field.PartFieldDefinition.Settings["BooleanFieldSettings.OffLabel"];
                                    }
                                }
                                else if (field.FieldDefinition.Name == "DateTimeField")
                                {
                                    output = field.DateTime.ToString();
                                }
                            }
                        }
                    }
                }
                
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <span data-id="@contentItem.Id" data-fieldid="@Html.FieldIdFor(m => m.Field.Ids)" class="content-creator-item">@Html.Raw(output)</span>
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", "Admin", new {Area= "Contents", id=contentItem.Id}, new { @class = "button grey"})
                    </td>
                    <td>
                        <span data-id="@contentItem.Id" class="content-creator-remove button grey">@T("Remove")</span>
                    </td>
                </tr>
            }
        </tbody>
    </table>

    <span id="btn-@Html.FieldIdFor(m => m.Field.Ids)" class="button">@T("Add")</span>

    @Html.HiddenFor(m => m.SelectedIds)
    <span class="hint">@settings.Hint</span>
</fieldset>

@using (Script.Foot())
{
    <script type="text/javascript">
        //<![CDATA[

        (function($) {
            var multiple = @(settings.Multiple ? "true" : "false");
            var addButton = $('#btn-@Html.FieldIdFor(m => m.Field.Ids)');
            var @Html.FieldIdFor(m => m.Field.Ids)_Template = '<tr><td>&nbsp;</td><td><span data-id="{contentItemId}" data-fieldid="@Html.FieldIdFor(m => m.Field.Ids)" class="content-creator-item">{edit-link}</span></td><td><span data-id="{contentItemId}" class="content-creator-remove button grey">@T("Remove")</span></td></tr>';

            var refreshIds = function() {
                var id = $('#@Html.FieldIdFor(m => m.SelectedIds)');
                id.val('');
                $("span[data-fieldid = @Html.FieldIdFor(m => m.Field.Ids)]").each(function() {
                    id.val(id.val() + "," + $(this).attr("data-id"));
                });

                var itemsCount = $("span[data-fieldid = @Html.FieldIdFor(m => m.Field.Ids)]").length;
                if (!multiple && itemsCount > 0) {
                    addButton.hide();
                } else {
                    addButton.show();
                }
            };
            refreshIds();
            addButton.click(function() {
                addButton.trigger("orchard-admin-ContentCreator-open", {
                    callback: function(data) {
                        var template = @Html.FieldIdFor(m => m.Field.Ids)_Template.replace(/\{contentItemId\}/g, data.id).replace(/\{edit-link\}/g,data.displayText);
                        var content = $(template);
                        $('#content-creator-@Html.FieldIdFor(m => m.Field.Ids) tbody').append(content);

                        refreshIds();
                        $('#save-message-@Html.FieldIdFor(m => m.Field.Ids)').show();
                    },
                    baseUrl: '@Url.Content("~/")',
                    contentType: '@settings.ContentType'
                });
            });

            $('#content-creator-@Html.FieldIdFor(m => m.Field.Ids) .content-creator-remove').live("click", function() {
                $(this).closest('tr').remove();
                refreshIds();
                $('#save-message-@Html.FieldIdFor(m => m.Field.Ids)').show();
            });

            $("#content-creator-@Html.FieldIdFor(m => m.Field.Ids) tbody").sortable({
                handle: 'td:first',
                stop: function() {
                    refreshIds();
                    $('#save-message-@Html.FieldIdFor(m => m.Field.Ids)').show();
                }
            }).disableSelection();


        })(jQuery);

        //]]>
    </script>
}